package com.audaque.springboot.foshanupload.shardingsphere.utils;

import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Component
public class ShardingUtil {

    private static Environment environment;

    private static final LocalDate firstDate = LocalDate.of(2018, 12, 1);
    private static final List<String> list1 = Arrays.asList("T_ZHY_PRESCRIPTION_ITEM", "T_ZHY_IO_LIST"); // 一月分一个的表
    private static final List<String> list6 = Arrays.asList("T_ZHY_REG", "T_ZHY_CASE_HIS", "T_ZHY_PRESCRIPTION"); // 6个月分一个的表


    public ShardingUtil(Environment environment) {
        this.environment = environment;
    }

    public static String getTableName(String logicTableName, Date date) {
        LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        // 相差几月
        long months = ChronoUnit.MONTHS.between(firstDate, localDate);

        // 测试的时候随机生成一个0-11的数，模拟放到不同的表
//        List<String> activies = Arrays.asList(environment.getActiveProfiles());
//        if (activies.contains("dev")) {
//            months = new Random().nextInt(11);
//        }

        long num = 1;
        if (list1.contains(logicTableName)) {
            num = months + 1;
        } else if (list6.contains(logicTableName)) {
            num = (long)Math.ceil(months / 6) + 1;
        }
        return logicTableName + "_" + num;
    }
}
